/// 页面 * 主界面 * 头右部菜单

import { Dropdown, Menu, Select } from 'ant-design-vue'
import type { DropdownProps, SelectProps } from 'ant-design-vue'
import { LoadingOutlined } from '@ant-design/icons-vue'
import { ExIcon, genComponent } from '@expresso/plus'
import { useFullscreen } from '@vueuse/core'
import { useRoute, useRouter } from 'vue-router'
import { menusRightCSS } from './styles'
import { useLoginStore, useMenusStore } from '@/stores'
import type { Menu as MenuType } from '@/stores'
import { apiLogout, apiLogoutLog, apiMergeLoginProject } from '@/apis/Login'
import { cache, isSucceed } from '@/helpers'

type ProjectMenu = Pick<SelectProps, 'open' | 'onChange' | 'getPopupContainer'> & {
  onOpen: (open: boolean) => void
}

type UserMenu = Pick<DropdownProps, 'getPopupContainer'> & {
  jump: (menu: MenuType) => void
  logout: () => void
}

//# 定义

/**
 * 头右部菜单
 */
export default genComponent({ name: 'MenusRight' }, () => {
  //# 成员

  //// 路由 ////

  const route = useRoute()

  //// 全局状态 ////

  /** 全局状态-登录 */
  const login = useLoginStore()
  //|
  /** 全局状态-菜单 */
  const menus = useMenusStore()

  //// 加载器 ////

  /** 加载器-项目列表 */
  const ploading = useLoading('local')
  //|
  /** 加载器-用户信息 */
  const uloading = useLoading('local')

  //// 菜单 ////

  /** 菜单-项目列表 */
  const menuProject = shallowReactive<ProjectMenu>({
    open: false,
    onOpen(open) {
      menuProject.open = open
    },
    getPopupContainer(triggerNode: HTMLDivElement) {
      return triggerNode?.parentElement?.parentElement?.getElementsByClassName(
        'popup-container',
      )[0] as any
    },
    onChange(value) {
      menuProject.open = false
      login.project.value = value as any
      if (login.project.value != null) {
        ploading(async () => {
          await apiMergeLoginProject(login.project.value!)
          setTimeout(() => {
            cache.setLoginInfo({
              ...cache.getLoginInfo()!,
              lastProjectId: login.project.value!,
            })
            location.href = route.fullPath
          })
        })
      }
    },
  })
  const router = useRouter()
  /** 菜单-用户信息 */
  const menuUser = shallowReactive<UserMenu>({
    getPopupContainer(triggerNode) {
      return triggerNode?.getElementsByClassName('popup-container')[0] as any
    },
    jump(menu) {
      if (menu.type === 'dir') {
        menus.keys.level1Keys = [menu.key]
        const memu = menus.data.level1Key2Menus[menu.key]?.[0]
        memu && menus.openMenu(memu)
      }
      else {
        if (!menu.linked) {
          menus.keys.levelsKeys = []
        }
        menus.openMenu(menu)
      }
    },
    logout() {
      uloading(async () => {
        const res = await apiLogout()
        if (isSucceed(res, false)) {
          const loginInfo = localStorage.getItem('loginInfo')
          const loginInfoJson = JSON.parse(loginInfo!)
          // 退出登录日志
          apiLogoutLog({
            reasonCode: 'manualLogout',
            userName: loginInfoJson?.userName,
            realName: loginInfoJson?.realName,
            userType: loginInfoJson?.userType,
            companyId: loginInfoJson?.companyId,
            lastProjectId: loginInfoJson?.lastProjectId,
            platformType: 10,
          }).then(() => {
            cache.removeToken()
            router.push('/login')
          })
        }
      })
    },
  })

  /** 菜单-全屏切换 */
  const menuFullScreen = useFullscreen()

  //# 渲染
  return () => (
    <div class={['menus-right', menusRightCSS]}>
      {/* 菜单-项目列表 */}
      {((route.path.toLocaleLowerCase() !== '/project/pro-list'
      && route.path.toLocaleLowerCase().startsWith('/project/'))
      || route.path.toLocaleLowerCase().startsWith('/iot/')
      || route.path.toLocaleLowerCase().startsWith('/dataease/')
      || route.path.toLocaleLowerCase().startsWith('/business/')) && (
        <div
          class="menu project"
          onMouseenter={() => menuProject.onOpen(true)}
          onMouseleave={() => menuProject.onOpen(false)}
        >
          <ExIcon type="hd-icon-yuanqu" />
          <Select
            v-model:value={login.project.value}
            open={menuProject.open}
            onChange={menuProject.onChange}
            getPopupContainer={menuProject.getPopupContainer}
            dropdownMatchSelectWidth={false}
          >
            {{
              default: () =>
                (login.project.options ?? []).map(({ label, value }) => (
                  <Select.Option key={value}>{label}</Select.Option>
                )),
              suffixIcon: () =>
                ploading.value
                  ? (
                    <LoadingOutlined class="hd-icon icon-loading" />
                    )
                  : (
                    <ExIcon type="hd-icon-arrow-prev" class="icon-arrow" />
                    ),
            }}
          </Select>
          <div class="popup-container" />
        </div>
      )}

      {/* 菜单-用户信息 */}
      <Dropdown placement="bottomRight" getPopupContainer={menuUser.getPopupContainer}>
        {{
          default: () => (
            <div class="menu user">
              <div class="user-abbr">{(login.user.realName ?? '')[0]}</div>
              <div class="user-name">{login.user.realName}</div>
              {uloading.value
                ? (
                  <LoadingOutlined class="hd-icon icon-loading" />
                  )
                : (
                  <ExIcon type="hd-icon-arrow-prev" class="icon-arrow" />
                  )}
              <div class="popup-container" />
            </div>
          ),
          overlay: () => (
            <Menu>
              <div class={['info']}>
                {/* 用户名称 */}
                <div class="title" title={login.user.realName}>
                  {login.user.realName}
                </div>
                {/* 用户角色 */}
                {/* {
                    login.role.list.map(({ roleName }) => (
                      <div class="item" title={roleName}>{roleName}</div>
                    ))
                  } */}
              </div>
              {/* 一级菜单 */}
              {menus.menusLevel1.right.map(menu => (
                <Menu.Item key={menu.key} onClick={() => menuUser.jump(menu)} icon={menu.icon}>
                  {menu.label}
                </Menu.Item>
              ))}
              <Menu.Item
                onClick={() => {
                  router.push('/user-center')
                }}
                icon={<ExIcon type="hd-icon-yonghu2" />}
              >
                个人中心
              </Menu.Item>
              <Menu.Item
                class="logout"
                onClick={menuUser.logout}
                icon={<ExIcon type="hd-icon-tuichu" />}
              >
                退出登录
              </Menu.Item>
            </Menu>
          ),
        }}
      </Dropdown>

      {/* 菜单-全屏切换 */}
      <div class="menu fullscreen" onClick={menuFullScreen.toggle}>
        {menuFullScreen.isFullscreen.value
          ? (
            <ExIcon type="hd-icon-zhankai2" />
            )
          : (
            <ExIcon type="hd-icon-zhankai1" />
            )}
      </div>
    </div>
  )
})
